import Cookies from "js-cookie";
//管理菜单相关的数据(es6语法，对象导出)
export default {
    state: {
        isCollapse: false, //控制菜单的展开还是收起
        tabList: [
            {
                path: "/",
                name: "home",
                label: "首页",
                icon: "s-home",
                url: "Home/Home",
            },
        ],  //面包屑数组
        menu: [

        ]
    },
    mutations: {
        //修改菜单展开和收起的方法
        collapseMenu(state) {
            state.isCollapse = !state.isCollapse
        },
        //更新面包屑数据(val为传进的数据)
        selectMenu(state, val) {
            console.log(val);
            //判断添加的数据是否为默认state（首页）
            if (val.name != 'home') {
                const index = state.tabList.findIndex(item => item.name == val.name);
                if (index == -1) {
                    state.tabList.push(val);
                }
            }
        },
        //删除指定的tags数据
        closeTags(state, item) {

            const index = state.tabList.findIndex(val => val.name == item.name);
            state.tabList.splice(index, 1);
        },
        //设置menu的数据
        setMenu(state, val) {
            state.menu = val;
            Cookies.set('menu', JSON.stringify(val));
        },
        //动态注册路由
        addMenu(state, router) {
            //判断缓存中是否有数据
            if (!Cookies.get('menu')) {
                return
            }
            const menu = JSON.parse(Cookies.get('menu'))
            state.menu = menu
            //处理动态路由的数据
            const menuArry = [];
            menu.forEach(item => {
                if (item.children) {
                    item.children = item.children.map(item => {
                        item.component = () => import(`../views/${item.url}`)
                        return item;
                    })
                    menuArry.push(...item.children)
                } else {
                    item.component = () => import(`../views/${item.url}`)
                    menuArry.push(item);
                }
            })
            console.log(menuArry)
            //路由的动态注册
            menuArry.forEach(item=>{
                router.addRoute('Main',item);
            })
        }
    }
}